import React, { useState, useRef, useEffect } from 'react';
import styles from './index.module.less';

export default function AI() {
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const chatContainerRef = useRef(null);
  const messagesEndRef = useRef(null);

  // 示例欢迎消息
  useEffect(() => {
    setMessages([
      // { role: 'assistant', content: '您好！我是DeepSeek AI助手，很高兴为您服务。' },
      { role: 'assistant', content: '请问有什么我可以帮助您的吗？' }
    ]);
  }, []);

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages]);

  // 解析流式响应
  const parseStreamResponse = (chunkText) => {
    const lines = chunkText.split('\n').filter(line => line.trim() !== '');
    let content = '';

    for (const line of lines) {
      if (line.startsWith('data: ')) {
        try {
          const data = JSON.parse(line.substring(6));
          // 正确的DeepSeek API响应结构
          if (data.choices && data.choices[0].delta && data.choices[0].delta.content) {
            content += data.choices[0].delta.content;
          }
          // 处理完成状态
          if (data.choices && data.choices[0].finish_reason) {
            break;
          }
        } catch (e) {
          console.warn('解析JSON失败，继续处理其他行:', e);
        }
      }
    }

    return content;
  };

  // 发送消息
  const sendMessage = async () => {
    if (!input.trim() || isLoading) return;

    const question = input.trim();
    setInput('');
    setIsLoading(true);

    // 添加用户消息
    setMessages(prev => [...prev, { role: 'user', content: question }]);

    try {
      // 真实的DeepSeek API调用
      const response = await fetch('https://api.deepseek.com/chat/completions', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${import.meta.env.VITE_DEEPSEEK_API_KEY}`,
        },
        body: JSON.stringify({
          model: 'deepseek-chat',
          messages: [
            { role: 'system', content: '你是一个有帮助的AI助手，用中文回答用户的问题。' },
            ...messages.map(msg => ({ role: msg.role, content: msg.content })),
            { role: 'user', content: question }
          ],
          stream: true,
          max_tokens: 2000,
          temperature: 0.7,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(`API请求失败: ${response.status} - ${errorData.message || response.statusText}`);
      }

      const reader = response.body.getReader();
      const decoder = new TextDecoder('utf-8');
      let aiContent = '';

      // 添加初始的AI消息占位
      setMessages(prev => [...prev, { role: 'assistant', content: '' }]);

      while (true) {
        const { done, value } = await reader.read();
        if (done) break;

        const chunkText = decoder.decode(value, { stream: true });
        const newContent = parseStreamResponse(chunkText);

        if (newContent) {
          aiContent += newContent;

          // 更新AI消息内容
          setMessages(prev => {
            const newMessages = [...prev];
            const lastMessage = newMessages[newMessages.length - 1];
            if (lastMessage && lastMessage.role === 'assistant') {
              newMessages[newMessages.length - 1] = {
                ...lastMessage,
                content: aiContent
              };
            }
            return newMessages;
          });
        }
      }
    } catch (err) {
      console.error('请求出错:', err);
      setMessages(prev => [...prev, {
        role: 'assistant',
        content: '抱歉，发生了错误，请稍后再试。错误信息: ' + err.message
      }]);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <h2 className={styles.title}>DeepSeek AI助手</h2>

      <div className={styles.chat}>
        <div ref={chatContainerRef} className={styles.chatBox}>
          {messages.map((message, index) => (
            <div
              key={index}
              className={`${styles.message} ${styles[message.role]}`}
            >
              <div className={styles.messageContent}>
                {message.content}
              </div>
            </div>
          ))}

          {isLoading && (
            <div className={`${styles.message} ${styles.assistant}`}>
              <div className={styles.messageContent}>
                <div className={styles.typingIndicator}>
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          )}

          <div ref={messagesEndRef} className={styles.scrollAnchor} />
        </div>
      </div>

      <div className={styles.inputArea}>
        <div className={styles.inputContainer}>
          <input
            type="text"
            placeholder="请输入您的问题..."
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && sendMessage()}
            disabled={isLoading}
          />
          <button
            onClick={sendMessage}
            disabled={isLoading || !input.trim()}
            className={styles.sendButton}
          >
            {isLoading ? '发送中...' : '发送'}
          </button>
        </div>
      </div>
    </div>
  );
}